//
//  UGImageLocation.swift
//  Alamofire
//
//  Created by admin on 2022/4/3.
//


/**
 图片本地操作
 */
import Foundation
import UIKit
import Photos

fileprivate extension Date{
    
   func toString(_ format:String="yyyy-MM-dd-HH-mm-ss") -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = format
        let date = formatter.string(from: self)
        return date
    }
}
public extension UIImage{
    
  
   @objc func ug_saveToloc(_ path:String?=nil)->String?{
       let path:String = path ?? UIApplication.KDocumnetPath.appending("/ugimage")
		guard let imageData = self.jpegData(compressionQuality: 1) as Data? else{
			return nil
		}
		let now = Date().toString()
       let rand = Int.random(in: 0..<10000)
		let imageName = "/\(now)-\(rand).png"
		if FileManager.isExists(path: path) == false{
			try! FileManager().createDirectory(at: .init(fileURLWithPath: path), withIntermediateDirectories: true,
											   attributes: nil)
		}
		let fullPath = path.appending(imageName)
		do{
			try imageData.write(to: .init(fileURLWithPath: fullPath))
			return imageName
		}catch{
			debugPrint(error)
			return nil
		}
	}
    
    @objc static func ug_saveToLoc(images:[UIImage], _ path:String?=nil)->[String]{
        let path:String = path ?? UIApplication.KDocumnetPath.appending("/ugimage")
        var imageNames:[String] = []
        images.forEach { image in
            if let name = image.ug_saveToloc(path){
                imageNames.append(name)
            }
        }
		return imageNames
	}
	
    @objc static func ug_locImage(_ name:String, _ path:String? = nil)->UIImage?{
        let path:String = path ?? UIApplication.KDocumnetPath.appending("/ugimage")
		let respath = path.appending(name)
        let image = UIImage(contentsOfFile: respath)
		return image
		
	}
    
    @objc static func ug_locUrl(_ name:String,_ path:String? = nil)->URL{
		
        let path:String = path ?? UIApplication.KDocumnetPath.appending("/ugimage")
		let respath = path.appending(name)
		if name.hasPrefix("http"){
			return URL.init(string: name) ?? .init(fileURLWithPath: respath)
		}

		return .init(fileURLWithPath: respath)
		
	}


}

public extension PHAsset{
    
    func image(_ block:@escaping (UIImage?, [AnyHashable : Any]?) -> Void){
        let option = PHImageRequestOptions()
        option.isNetworkAccessAllowed = true //允许下载iCloud的图片
        option.resizeMode = .fast
        option.deliveryMode = .fastFormat
        PHImageManager.default().requestImage(for: self,
                                              targetSize: .zero,
                                              contentMode: .aspectFill,
                                              options: option,
                                              resultHandler: block)
        
    }
	

	
	
    
}


